package org.saxonextensions.eml.emitter;

import javax.mail.*;
import java.util.Properties;
import java.util.logging.Logger;
import java.util.logging.Level;

/**
 * A simple mail session factory
 *
 * User: ivan
 * Date: 22-Jun-2004
 * Time: 12:34:43 PM
 */
public class MailSessionFactory {

  /** Instance */
  private static MailSessionFactory ourInstance;

  public static MailSessionFactory getInstance() {
    if (ourInstance == null) ourInstance = new MailSessionFactory();
    return ourInstance;
  }

  /**
   * Return mailsession
   *
   * @return mail session
   * @throws Exception when unable to create a session
   */
  public static Session getSession() throws Exception {
    return getInstance().getMailSession();
  }

  /** Component logger */
  protected Logger logger = Logger.getLogger(this.getClass().getName());

  /** Properties */
  protected Properties props = System.getProperties();

  /**
   * Return properties
   *
   * @return properties
   */
  public Properties getProps() {
    return props;
  }

  /**
   * Set properties
   *
   * @param props properties
   */
  public void setProps(Properties props) {
    this.props = props;
  }

  /**
   * Return SMTP Session for given SMTP Host
   *
   * @return SMTP Session
   * @throws Exception when SMTP session could not be constructed
   */
  public Session getMailSession() throws Exception {
    Session session;
    try {
      logger.log(Level.FINEST, "Getting the session.");
      // Obtain mail session
      session = Session.getInstance(props);

    } catch (Exception e) {
      logger.log(Level.SEVERE, "Unable to construct SMTP Session.", e);
      throw e;
    }
    return session;
  }

}

